// miniprogram/pages/admin/customer/selectCustomer/selectCustomer.js
const app = getApp();
const db = wx.cloud.database();
const _ = db.command;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    items: [],
    itemIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    const that = this;
    // TODO 添加搜索框
    app.login(user=>{
      if (!user.studioid) {
        wx.navigateBack();
        return;
      }
      this.loadItems();
    })
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('setCustomer', function(data) {
      console.log(data)
      if (data._id && that.data.items){
        that.data.items.map((v,i)=>{
          if (v._id == data._id){
            that.setData({itemIndex: i});
            return false;
          }
        })
      }
    })
    
  },

  loadItems: function(e){
    const that = this;
    app.login(user => {
      wx.showNavigationBarLoading();
      wx.cloud.callFunction({
        name: 'crud',
        data: {
          op: 'get',
          table: 'customer',
          skip: 0,
          where: {
            studioid: user.studioid
          }
          // orderBy: [{'updatetime': desc}]
        },
        success: res => {
          that.setData({
            items: res.result.data
          })
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
        }
      })
    })
  },

  
  selectCustomer: function(e){
    console.log(e.currentTarget.dataset.index);
    const index = e.currentTarget.dataset.index;
    let customer = this.data.items[index];
    this.getOpenerEventChannel().emit('setCustomer', {customer: customer});
    wx.navigateBack();
  },

  searchCustomer: function(e){

    const form = e.detail.value;
    const that = this;
    if (!form.name){
      this.loadItems();
      return;
    }
    wx.showNavigationBarLoading();
      wx.cloud.callFunction({
        name: 'customer',
        data: {
          op: 'search',
          studioid: app.globalData.user.studioid,
          name: form.name
          // orderBy: [{'updatetime': desc}]
        },
        success: res => {
          console.log(res.result);
          that.setData({
            items: res.result.list
          })
          wx.hideNavigationBarLoading();
          //停止下拉刷新
          wx.stopPullDownRefresh();
        }
      })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})